package org.ihelpuoo.parser.segment;

import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;

import org.ihelpuoo.lang.ObjectUtils;
import org.ihelpuoo.parser.StringTraveler;

public class PlugPoint extends SegmentNode
{
	private String			name;
	private List<Object>	values;

	@Override
	void valueOf(StringTraveler st)
	{
		clear();
		name = st.next(marks.markRight());
		stack().push(st.current());
		if (null == name)
			throw new RuntimeException("Syntax Error: expect a close char \"" + marks.markRight()
					+ "\"");
	}

	public String getName()
	{
		return name;
	}

	@Override
	public void clear()
	{
		values = new LinkedList<Object>();
	}

	public void setValue(Object value)
	{
		if (values.size() == 0)
			values.add(value);
		else if (values.size() == 1)
			values.set(0,value);
		else
		{
			values.clear();
			values.add(value);
		}
		if (value instanceof CharSegment)
			getSegment().registSubPlugPointMap((CharSegment)value);
	}

	public void addValue(Object value)
	{
		values.add(value);
	}

	@Override
	public CharSequence evaluate()
	{
		if (values.size() == 0)
			return "";
		if (values.size() == 1)
			if (null == values.get(0))
				return "";
			else
				return ObjectUtils.castObjectToCharSequence(values.get(0)).toString();
		StringBuffer sb = new StringBuffer();
		Iterator it = values.iterator();
		while (it.hasNext())
		{
			sb.append(ObjectUtils.castObjectToCharSequence(it.next()));
		}
		return sb;
	}

	@Override
	public SegmentNode duplicate()
	{
		PlugPoint node = new PlugPoint();
		node.name = this.name;
		return node;
	}

	@Override
	public String toString()
	{
		return evaluate().toString();
	}
}
